package com.xayy.mgt.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.CalendarUtil;
import cn.hutool.core.date.DateUtil;
import cn.kawins.base.result.CheckResult;
import cn.kawins.base.utils.BeanUtil;
import cn.kawins.base.utils.StringUtil;
import cn.kawins.base.utils.TreeUtil;
import cn.kawins.mybatis.base.BaseServiceImpl;
import cn.kawins.mybatis.util.SnowflakeId;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.page.PageMethod;
import com.xayy.core.antlr4.model.TelemetryVo;
import com.xayy.core.config.datasource.DataSourceParam;
import com.xayy.core.config.datasource.DataSourceProperties;
import com.xayy.core.constant.BayesArgs;
import com.xayy.mgt.mapper.AssociationParameterMapper;
import com.xayy.mgt.mapper.BayesMapper;
import com.xayy.mgt.mapper.NodeInfoMapper;
import com.xayy.mgt.mapper.NodeInfoRelationMapper;
import com.xayy.mgt.model.*;
import com.xayy.mgt.model.dto.NodeInfoDto;
import com.xayy.mgt.model.dto.TelemetryDto;
import com.xayy.mgt.model.vo.NodeTreeCopyInfoVo;
import com.xayy.mgt.model.vo.NodeTreeInfoVo;
import com.xayy.mgt.model.vo.TimeAxisVo;
import com.xayy.mgt.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author Nie
 * @version V1.0
 * @date 2023/8/14 15:17
 */
@Service
public class NodeInfoServiceImpl extends BaseServiceImpl<NodeTreeInfo> implements NodeInfoService {

    @Resource
    private NodeInfoMapper nodeInfoMapper;

    @Resource
    private NodeInfoRelationMapper nodeInfoRelationMapper;

    @Resource
    private NodeParamInfoService nodeParamInfoService;
//    @Autowired
//    private AssociationParameterService parameterService;

    @Autowired
    private AssociationParameterMapper parameterMapper;

    @Autowired
    private HealthDeepService healthDeepService;

    @Autowired
    private FunctionalIndicatorsService functionalIndicatorsService;
    @Autowired
    private PerformanceIndicatorsService performanceIndicatorsService;
    @Resource
    private BayesMapper bayesMapper;
    @Autowired
    private BayesArgs bayesArgs;
    @Autowired
    private SystemTelemetryService systemTelemetryService;

    private static DataSourceParam dataSourceParam;

    @Autowired
    public void setDataSourceParam(DataSourceParam dataSourceParam){
        NodeInfoServiceImpl.dataSourceParam = dataSourceParam;
    }


    @Override
    public CheckResult<Object> getNodeTree(Long nodeId) {
        List<NodeTreeInfo> nodeTreeInfos = getNodeInfoList(nodeId).getData();
        if (CollUtil.isEmpty(nodeTreeInfos)) {
            return CheckResult.fail("卫星结构信息不存在");
        }
        List<NodeTreeInfoVo> treeInfoVos = nodeTreeInfos.stream().map(x -> BeanUtil.copyBean(x, NodeTreeInfoVo.class)).collect(Collectors.toList());
        /*查询所有节点最新评估的健康数据*/
        List<Long> nodeIds = treeInfoVos.stream().map(NodeTreeInfoVo::getId).collect(Collectors.toList());
        Example example = new Example(HealthDeep.class);
        example.createCriteria().andIn("nodeId",nodeIds);
        List<HealthDeep> healthDeeps = healthDeepService.selectByExample(example);

        for (NodeTreeInfoVo x : treeInfoVos) {
            x.setName(x.getNodeName());
            HashMap<String, Object> map = new HashMap<>();
            HealthDeep deep = healthDeeps.stream().filter(f -> f.getNodeId().equals(x.getId())).findFirst().orElse(null);
            if (deep != null && StringUtil.isNotBlank(deep.getDataInfo())) {
                double score = Double.parseDouble(deep.getDataInfo());
                if (score >= 90D && score <= 100D) {
                    map.put("borderColor", "#4CFF00");
                    x.setLabel(map);
                } else if (score >= 80D && score <= 89D) {
                    map.put("borderColor", "#00F7FF");
                    x.setLabel(map);
                } else if (score >= 60D && score <= 79D) {
                    map.put("borderColor", "#FFBF00");
                    x.setLabel(map);
                } else if (score >= 0D && score <= 59D) {
                    map.put("borderColor", "#FF0000");
                    x.setLabel(map);
                }
            }
        }
        NodeTreeInfo nodeTreeInfo = selectById(nodeId);
        List<NodeTreeInfoVo> tree = TreeUtil.toTree(nodeTreeInfo.getParentId(), treeInfoVos);
        return CheckResult.success(tree.get(0));
    }

    @Transactional
    @Override
    public CheckResult<Object> addOrUpdate(NodeTreeInfo nodeTreeInfo) {
        if (nodeTreeInfo.getId() == null) {
            // 设置层级
            Integer level = setlevel(nodeTreeInfo);
            nodeTreeInfo.setLevel(level);
            Long id = new SnowflakeId().genId("node_tree_info", "id");
            nodeTreeInfo.setId(id);
            // 添加分系统信息，分系统level为1
            Long systemId = getSystemInfo(nodeTreeInfo);
            nodeTreeInfo.setSystemId(systemId);
            NodeTreeInfo parent = selectById(nodeTreeInfo.getParentId());
            if (BeanUtil.isNotEmpty(parent)) {
                nodeTreeInfo.setSatelliteId(parent.getSatelliteId());
            }
            if (level == 0) {
                nodeTreeInfo.setSatelliteId(id);
            }
            CheckResult<String> checkName = checkName(false, nodeTreeInfo);
            if (checkName.no()) {
                return CheckResult.fail(checkName.getCheckMsg());
            }
            CheckResult<String> checkcode = checkCode(false, nodeTreeInfo);
            if (checkcode.no()) {
                return CheckResult.fail(checkcode.getCheckMsg());
            }
            insert(nodeTreeInfo);
            if (level > 0) {
                // 新增关联关系
                NodeInfoRelation nodeInfoRelation = NodeInfoRelation.builder()
                        .satelliteId(nodeTreeInfo.getSatelliteId()).from(nodeTreeInfo.getParentId()).to(id)
                        .ids(nodeTreeInfo.getParentId().toString() + ":" + id.toString()).build();
                nodeInfoRelationMapper.insert(nodeInfoRelation);
            }
        } else {
            CheckResult<String> checkName = checkName(true, nodeTreeInfo);
            if (checkName.no()) {
                return CheckResult.fail(checkName.getCheckMsg());
            }
            CheckResult<String> checkcode = checkCode(true, nodeTreeInfo);
            if (checkcode.no()) {
                return CheckResult.fail(checkcode.getCheckMsg());
            }
            nodeTreeInfo.setSystemId(null);
            nodeTreeInfo.setLevel(null);
            updateByIdSelective(nodeTreeInfo);
        }
        return CheckResult.success();
    }

    @Transactional
    @Override
    public CheckResult<Object> copyTreeAndNode(NodeTreeCopyInfoVo vo) {

        /*查询复制的节点信息*/
        NodeTreeInfo nodeTreeInfo = selectById(vo.getCopyNodeId());
        if(nodeTreeInfo == null){
            return CheckResult.fail("复制的节点信息不存在");
        }
        Long id = new SnowflakeId().genId("node_tree_info", "id");
        nodeTreeInfo.setId(id);
        nodeTreeInfo.setSatelliteId(id);
        nodeTreeInfo.setLevel(0);
        nodeTreeInfo.setNodeName(vo.getNodeName());
        nodeTreeInfo.setNodeCode(vo.getNodeCode());
        nodeTreeInfo.setParentId(vo.getCopyNodeParentId());
        /*校验名称和code是否重复*/
        CheckResult<String> checkcode = checkCode(false, nodeTreeInfo);
        if (checkcode.no()) {
            return CheckResult.fail(checkcode.getCheckMsg());
        }
        CheckResult<String> checkName = checkName(false, nodeTreeInfo);
        if (checkName.no()) {
            return CheckResult.fail(checkName.getCheckMsg());
        }
        /*插入复制的节点数据*/
        insert(nodeTreeInfo);
        /*复制子节点：根据卫星id获取原节点的所有子节点*/
        List<NodeTreeInfo> nodeTreeInfoList = getNodeInfoList(vo.getSatelliteId()).getData();
        /*获取所有节点ID*/
        List<Long> nodeIds = nodeTreeInfoList.stream().map(NodeTreeInfo::getId).collect(Collectors.toList());

        /*去掉level为0 的数据*/
        List<NodeTreeInfo> nodeTreeInfos = nodeTreeInfoList.stream().filter(f -> f.getLevel() != 0).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(nodeTreeInfos)) {
            /*获取所有的不同的ID*/
            Map<Long,Long> ids = new HashMap<>();
            nodeTreeInfos.forEach(item ->{
                if(item.getId() != null){
                    ids.put(item.getId(),null);
                }
                if(item.getSystemId() != null){
                    ids.put(item.getSystemId(),null);
                }
                if(item.getParentId() != null){
                    ids.put(item.getParentId(),null);
                }
            });
            /*生成新的对应id关系*/
            ids.forEach((k,v) ->{
                /*如果是卫星id则更改为已生成的id*/
                if(k.equals(vo.getCopyNodeId())){
                    ids.put(k,id);
                }else{
                    ids.put(k,new SnowflakeId().genId("node_tree_info", "id"));
                }
            });
            /*ID替换大法*/
            nodeTreeInfos.forEach(item ->{
                item.setSatelliteId(id);
                item.setId(ids.get(item.getId()));
                item.setSystemId(ids.get(item.getSystemId()));
                item.setParentId(ids.get(item.getParentId()));
                item.setCreatedTime(new Date());
            });
            /*查询节点对应关系*/
            List<NodeInfoRelation> select = nodeInfoRelationMapper.select(NodeInfoRelation.builder().satelliteId(vo.getSatelliteId()).build());
            List<NodeInfoRelation> filedList = new ArrayList<>();
            /*ID替换大法*/
            select.forEach(item ->{
                /*数据出现问题的，无对应关系的数据丢弃*/
                if(ids.get(item.getFrom()) == null || ids.get(item.getTo()) == null){
                    filedList.add(item);
                    return;
                }
                item.setSatelliteId(id);
                item.setId(new SnowflakeId().genId("node_tree_info", "id"));
                item.setFrom(ids.get(item.getFrom()));
                item.setTo(ids.get(item.getTo()));
                item.setCreatedTime(new Date());
            });
            select.removeAll(filedList);
            /*插入子节点数据和关系数据*/
            if(CollUtil.isNotEmpty(select)){
                nodeInfoRelationMapper.insertList(select);
            }
            if(CollUtil.isNotEmpty(nodeTreeInfos)){
                insertList(nodeTreeInfos);
            }
            /*关联参数配置信息*/
            Example exampleParam = new Example(AssociationParameter.class);
            Example.Criteria criteriaParam = exampleParam.createCriteria();
            criteriaParam.andIn("nodeId",nodeIds);
//            List<AssociationParameter> associationParameters = parameterService.selectByExample(exampleParam);
            List<AssociationParameter> associationParameters = parameterMapper.selectByExample(exampleParam);
            associationParameters.forEach(item ->{
                item.setId(new SnowflakeId().genId("node_tree_info", "id"));
                item.setNodeId(ids.get(item.getNodeId()));
                item.setParamNodeId(ids.get(item.getParamNodeId()));
                item.setCreatedTime(new Date());
            });
            /*插入*/
            if(CollUtil.isNotEmpty(associationParameters)){
                parameterMapper.insertList(associationParameters);
//                parameterService.insertList(associationParameters);
            }
            /*健康度配置信息*/
            Example exampleHealth = new Example(HealthDeep.class);
            Example.Criteria criteriaHealth = exampleHealth.createCriteria();
            criteriaHealth.andIn("nodeId",nodeIds);
            List<HealthDeep> healthDeeps = healthDeepService.selectByExample(exampleHealth);
            healthDeeps.forEach(item ->{
                item.setId(new SnowflakeId().genId("node_tree_info", "id"));
                item.setNodeId(ids.get(item.getNodeId()));
                item.setCreatedTime(new Date());
            });
            /*插入*/
            if(CollUtil.isNotEmpty(healthDeeps)){
                healthDeepService.insertList(healthDeeps);
            }
            /*功能指标项配置信息*/
            Example exampleFunctional = new Example(FunctionalIndicators.class);
            Example.Criteria criteriaFunctional = exampleFunctional.createCriteria();
            criteriaFunctional.andIn("nodeId",nodeIds);
            List<FunctionalIndicators> functionalIndicators = functionalIndicatorsService.selectByExample(exampleFunctional);
            functionalIndicators.forEach(item ->{
                item.setId(new SnowflakeId().genId("node_tree_info", "id"));
                item.setNodeId(ids.get(item.getNodeId()));
                item.setCreatedTime(new Date());
            });
            /*插入*/
            if(CollUtil.isNotEmpty(functionalIndicators)){
                functionalIndicatorsService.insertList(functionalIndicators);
            }
            /*性能指标项配置信息*/
            Example examplePerformance = new Example(PerformanceIndicators.class);
            Example.Criteria criteriaPerformance = examplePerformance.createCriteria();
            criteriaPerformance.andIn("nodeId",nodeIds);
            List<PerformanceIndicators> performanceIndicators = performanceIndicatorsService.selectByExample(examplePerformance);
            performanceIndicators.forEach(item ->{
                item.setId(new SnowflakeId().genId("node_tree_info", "id"));
                item.setNodeId(ids.get(item.getNodeId()));
                item.setCreatedTime(new Date());
            });
            /*插入*/
            if(CollUtil.isNotEmpty(performanceIndicators)){
                performanceIndicatorsService.insertList(performanceIndicators);
            }
            /*查询原始节点的参数*/
            Example nodeParamExample = new Example(NodeParamInfo.class);
            Example.Criteria criteriaNodeParam = nodeParamExample.createCriteria();
            criteriaNodeParam.andIn("nodeId",nodeIds);
            List<NodeParamInfo> nodeParamInfos = nodeParamInfoService.selectByExample(nodeParamExample);
            nodeParamInfos.forEach(item ->{
                item.setId(new SnowflakeId().genId("t_node_param_info", "id"));
                item.setNodeId(ids.get(item.getNodeId()));
                item.setSatelliteId(id);
                item.setCreatedTime(new Date());
            });
            /*插入*/
            if(CollUtil.isNotEmpty(nodeParamInfos)){
                nodeParamInfoService.insertList(nodeParamInfos);
            }
        }
        return CheckResult.success("复制成功");
    }

    @Override
    public List<NodeTreeInfo> getChildNode(Long parentNodeId) {
        return nodeInfoMapper.select(NodeTreeInfo.builder().parentId(parentNodeId).build());
    }

    @Override
    public List<NodeTreeInfo> getAllSatelliteList() {
        return select(NodeTreeInfo.builder().level(0).build());
    }


    @Override
    public CheckResult<Object> deleteTreeById(Long id) {
        /*查询节点是否存在子节点，存在则不允许删除*/
        int count = selectCount(NodeTreeInfo.builder().parentId(id).build());
        if (count > 0) {
            return CheckResult.fail("该节点存在子节点，不允许删除，如需删除请先删除子节点。");
        }
        int result = deleteById(id);
        // 删除节点下得关联参数性能功能健康指标
        parameterMapper.deleteByPrimaryKey(id);
//        parameterService.deleteByNodeId(id);
        functionalIndicatorsService.deleteByNodeId(id);
        performanceIndicatorsService.deleteByNodeId(id);
        healthDeepService.deleteByNodeId(id);
        if (result > 0) {
            return CheckResult.success("删除成功");
        }
        return CheckResult.fail("删除失败");
    }

    /**
     * 名称重复校验
     *
     * @param isUpdate     是否更新
     * @param nodeTreeInfo 入参
     * @return 结果日志
     */
    private CheckResult<String> checkName(Boolean isUpdate, NodeTreeInfo nodeTreeInfo) {
        Example example = new Example(NodeTreeInfo.class);
        Example.Criteria criteria = example.createCriteria();
        if (nodeTreeInfo.getLevel() == 0) {
            criteria.andEqualTo("parentId", nodeTreeInfo.getParentId());
        } else {
            criteria.andEqualTo("satelliteId", nodeTreeInfo.getSatelliteId());
        }
        criteria.andEqualTo("nodeName", nodeTreeInfo.getNodeName());
        if (Boolean.TRUE.equals(isUpdate)) {
            criteria.andNotEqualTo("id", nodeTreeInfo.getId());
        }
        List<NodeTreeInfo> nodeTreeInfos = selectByExample(example);
        if (CollUtil.isNotEmpty(nodeTreeInfos)) {
            return CheckResult.fail("节点名称：" + nodeTreeInfo.getNodeName() + ",已存在");
        }
        return CheckResult.success();
    }

    /**
     * 校验节点code是否重复
     *
     * @param isUpdate     是否更新
     * @param nodeTreeInfo 入参
     * @return 结果日志
     */
    private CheckResult<String> checkCode(Boolean isUpdate, NodeTreeInfo nodeTreeInfo) {
        Example example = new Example(NodeTreeInfo.class);
        Example.Criteria criteria = example.createCriteria();
        if (nodeTreeInfo.getLevel() == 0) {
            criteria.andEqualTo("parentId", nodeTreeInfo.getParentId());
        } else {
            criteria.andEqualTo("satelliteId", nodeTreeInfo.getSatelliteId());
        }
        criteria.andEqualTo("nodeCode", nodeTreeInfo.getNodeCode());
        if (Boolean.TRUE.equals(isUpdate)) {
            criteria.andNotEqualTo("id", nodeTreeInfo.getId());
        }
        List<NodeTreeInfo> nodeTreeInfos = selectByExample(example);
        if (CollUtil.isNotEmpty(nodeTreeInfos)) {
            return CheckResult.fail("节点Code：" + nodeTreeInfo.getNodeCode() + ",已存在");
        }
        return CheckResult.success();
    }

    /**
     * 新增节点设置节点层级卫星节点为0
     *
     * @param nodeTreeInfo 入参
     * @return 层级
     */
    private Integer setlevel(NodeTreeInfo nodeTreeInfo) {
        NodeTreeInfo parent = selectById(nodeTreeInfo.getParentId());
        if (BeanUtil.isNotEmpty(parent)) {
            return parent.getLevel() + 1;
        }
        return 0;
    }

    /**
     * 新增节点设置节点分系统id，卫星和分系统节点为null
     *
     * @param nodeTreeInfo 入参
     * @return 分系统id
     */
    private Long getSystemInfo(NodeTreeInfo nodeTreeInfo) {
        if (nodeTreeInfo.getLevel() > 0) {
            if (nodeTreeInfo.getLevel() == 1) {
                // 分系统本身子
                return nodeTreeInfo.getId();
            }
            NodeTreeInfo parent = selectById(nodeTreeInfo.getParentId());
            return parent.getSystemId();
        }
        return null;
    }

    @Override
    public PageInfo<NodeTreeInfo> pageList(NodeInfoDto nodeInfoDto) {
        PageMethod.startPage(nodeInfoDto.getPage(), nodeInfoDto.getSize());
        List<NodeTreeInfo> nodeInfoList = nodeInfoMapper.pageList(nodeInfoDto);
        return new PageInfo<>(nodeInfoList);
    }

    @Override
    public CheckResult<Object> getNodeRelation(Long parentId) {
        HashMap<String, Object> map = new HashMap<>();
        List<NodeTreeInfo> nodeTreeInfos = getNodeInfoList(parentId).getData();
        ArrayList<NodeInfoRelation> nodeInfoRelations = new ArrayList<>();
        if (CollUtil.isEmpty(nodeTreeInfos)) {
            List<NodeTreeInfo> nodeTreeInfoList = select((NodeTreeInfo.builder().parentId(parentId)).build());
            List<NodeInfoRelation> extraArray =
                    nodeInfoRelationMapper.select(NodeInfoRelation.builder().from(parentId).build());
            for (NodeInfoRelation nodeInfoRelation : extraArray) {
                nodeInfoRelation
                        .setIds(nodeInfoRelation.getFrom().toString() + ":" + nodeInfoRelation.getTo().toString());
                nodeInfoRelations.add(nodeInfoRelation);
            }
            map.put("nodesArray", nodeTreeInfoList);
            map.put("edgesArray", extraArray);
        } else {
            for (NodeTreeInfo nodeTreeInfo : nodeTreeInfos) {
                List<NodeInfoRelation> select =
                        nodeInfoRelationMapper.select(NodeInfoRelation.builder().from(nodeTreeInfo.getId()).build());
                if (CollUtil.isNotEmpty(select)) {
                    for (NodeInfoRelation nodeInfoRelation : select) {
                        nodeInfoRelation
                                .setIds(nodeInfoRelation.getFrom().toString() + ":" + nodeInfoRelation.getTo().toString());
                        nodeInfoRelations.add(nodeInfoRelation);
                    }
                }
            }
            map.put("nodesArray", nodeTreeInfos);
            map.put("edgesArray", nodeInfoRelations);
        }

        return CheckResult.success(map);
    }

    @Override
    public CheckResult<Object> getNodeBaseInfo(Long nodeId) {
        NodeTreeInfo nodeInfo = selectById(nodeId);
        NodeTreeInfoVo nodeTreeInfoVo = BeanUtil.copyBean(nodeInfo, NodeTreeInfoVo.class);
        /*获取当前节点参数信息*/
        CheckResult<List<NodeParamInfo>> params = nodeParamInfoService.getParams(nodeId);
        if (params.ok()) {
            nodeTreeInfoVo.setNodeParamInfoList(params.getData());
        }
        return CheckResult.success(nodeTreeInfoVo);
    }

    @Override
    public CheckResult<List<NodeTreeInfo>> getNodeInfoList(Long satId) {
        List<NodeTreeInfo> nodeTreeInfos = select(NodeTreeInfo.builder().satelliteId(satId).build());
        return CheckResult.success(nodeTreeInfos);
    }

    @Override
    public CheckResult<Object> getInfo(Long nodeId) {
        NodeTreeInfo nodeInfo = selectById(nodeId);
        if (BeanUtil.isEmpty(nodeInfo)) {
            return CheckResult.fail("为获取到节点的信息");
        }
        int healthSize = healthDeepService.selectCount(HealthDeep.builder().nodeId(nodeId).build());
        int associationSize = parameterMapper.selectCount(AssociationParameter.builder().nodeId(nodeId).build());
//        parameterService.selectCount(AssociationParameter.builder().nodeId(nodeId).build());
        int functionSize =
                functionalIndicatorsService.selectCount(FunctionalIndicators.builder().nodeId(nodeId).build());
        int performanceSize =
                performanceIndicatorsService.selectCount(PerformanceIndicators.builder().nodeId(nodeId).build());
        Map<String, Object> result = new HashMap<>();
        result.put("satelliteId", nodeInfo.getSatelliteId());
        result.put("nodeId", nodeId);
        result.put("nodeName", nodeInfo.getNodeName());
        result.put("healthSize", healthSize);
        result.put("functionSize", functionSize);
        result.put("performanceSize", performanceSize);
        result.put("associationSize", associationSize);
        return CheckResult.success(result);
    }

    @Override
    public NodeTreeInfo getNode(Long nodeId) {
        NodeTreeInfo nodeInfo = selectById(nodeId);
        return nodeInfo;
    }

    @Override
    public List<NodeTreeInfo> getByParentId(Long parentId) {
        List<NodeTreeInfo> nodeTreeInfoList = nodeInfoMapper.selectByParentId(parentId);
        return nodeTreeInfoList;
    }

    @Override
    public CheckResult<Object> timeAxisData(long parseLong, String sDate, String eDate) {
        NodeTreeInfo nodeTreeInfo = selectById(parseLong);
        if(nodeTreeInfo == null){
            return CheckResult.fail("暂无该节点数据");
        }
        HashMap<String, Object> map = new HashMap<>();
        LocalDateTime startTime =
                LocalDateTime.ofInstant(DateUtil.parse(sDate, "yyyy-MM-dd").toInstant(), ZoneId.systemDefault());
        LocalDateTime endTime =
                LocalDateTime.ofInstant(DateUtil.parse(eDate, "yyyy-MM-dd").toInstant(), ZoneId.systemDefault());
        List<Date> time = dateZones(startTime, endTime);
        ArrayList<String> timeList = new ArrayList<>();
        for (Date date : time) {
            String format = DateUtil.format(date, "yyyy-MM-dd");
            timeList.add(format);
        }
        ArrayList<Object> finalList = new ArrayList<>();
        for (String times : timeList) {
            TimeAxisVo timeAxisVo = new TimeAxisVo();
            timeAxisVo.setDate(times);
            List<NodeTreeInfo> allNodeList =
                    nodeInfoMapper.select(NodeTreeInfo.builder().satelliteId(parseLong).build());
            List<NodeTreeInfoVo> treeInfoVos =
                    allNodeList.stream().map(x -> BeanUtil.copyBean(x, NodeTreeInfoVo.class)).collect(Collectors.toList());
            for (NodeTreeInfoVo x : treeInfoVos) {
                x.setName(x.getNodeName());
                String format = DateUtil.format(x.getCreatedTime(), "yyyy-MM-dd");
                if(x.getOverallScore() == null){
                    if (times.equals(format)) {
                        map.put("borderColor", "#4CFF00");
                        x.setLabel(map);
                    }
                    continue;
                }
                if (x.getOverallScore() >= 90 && x.getOverallScore() <= 100) {
                    if (times.equals(format)) {
                        map.put("borderColor", "#4CFF00");
                        x.setLabel(map);
                    }
                } else if (x.getOverallScore() >= 80 && x.getOverallScore() <= 89) {
                    if (times.equals(format)) {
                        map.put("borderColor", "#00F7FF");
                        x.setLabel(map);
                    }
                } else if (x.getOverallScore() >= 60 && x.getOverallScore() <= 79) {
                    if (times.equals(format)) {
                        map.put("borderColor", "#FFBF00");
                        x.setLabel(map);
                    }
                } else if (x.getOverallScore() >= 0 && x.getOverallScore() <= 59) {
                    if (times.equals(format)) {
                        map.put("borderColor", "#FF0000");
                        x.setLabel(map);
                    }
                }
            }
            List<NodeTreeInfoVo> tree = TreeUtil.toTree(nodeTreeInfo.getParentId(), treeInfoVos);
            timeAxisVo.setData(tree);
            finalList.add(timeAxisVo);
        }
        return CheckResult.success(finalList);
    }

    @Override
    public CheckResult<Object> bayesLeftTree(Long nodeId,String nodeCode) {
        NodeTreeInfo nodeTreeInfo = selectById(nodeId);
        if (BeanUtil.isEmpty(nodeTreeInfo))
            return CheckResult.fail("未找到左侧树配置节点信息");
        List<NodeTreeInfo> nodeTreeInfos = select(NodeTreeInfo.builder().satelliteId(nodeTreeInfo.getSatelliteId()).build());
        if (CollUtil.isEmpty(nodeTreeInfos)) {
            return CheckResult.fail("卫星结构信息不存在");
        }
        List<NodeTreeInfoVo> treeInfoVos = nodeTreeInfos.stream().map(x -> BeanUtil.copyBean(x, NodeTreeInfoVo.class)).collect(Collectors.toList());
        List<NodeTreeInfoVo> tree = TreeUtil.toTree(nodeTreeInfo.getId(), treeInfoVos);
        NodeTreeInfoVo nodeTreeInfoVo = BeanUtil.copyBean(nodeTreeInfo, NodeTreeInfoVo.class);
        nodeTreeInfoVo.setChildren(tree);
        return CheckResult.success(cn.kawins.base.utils.CollUtil.newArrayList(nodeTreeInfoVo));
    }

    @Override
    public CheckResult<List<Long>> getChildIds(Long satelliteId, Long nodeId) {
        List<Long> ids = new ArrayList<>();
        ids.add(nodeId);
        List<NodeTreeInfo> nodeTreeInfos = select(NodeTreeInfo.builder().satelliteId(satelliteId).build());
        if (CollUtil.isEmpty(nodeTreeInfos))
            return CheckResult.fail("没有找到对应卫星结构");
        List<NodeTreeInfoVo> treeInfoVos =
                nodeTreeInfos.stream().map(x -> BeanUtil.copyBean(x, NodeTreeInfoVo.class)).collect(Collectors.toList());
        List<NodeTreeInfoVo> tree = TreeUtil.toTree(nodeId, treeInfoVos);
        if (CollUtil.isNotEmpty(tree)) {
            List<NodeTreeInfoVo> list = TreeUtil.toList(tree);
            List<Long> idList = list.stream().map(NodeTreeInfoVo::getId).collect(Collectors.toList());
            ids.addAll(idList);
        }
        return CheckResult.success(ids);
    }

    public static String changeSql(String sql){
        if(StringUtil.isBlank(sql)){
            return sql;
        }
        List<DataSourceProperties> list = dataSourceParam.getList();
        if(list.isEmpty()){
            return sql;
        }
        String sourceName = list.get(0).getSourceName();
        /*如果是达梦数据库则需要替换符号*/
        if("DM8".equals(sourceName)){
            return sql.replace("`","\"");
        }else{
            return sql;
        }
    }
    public static String getDataBaseSource(){
        List<DataSourceProperties> list = dataSourceParam.getList();
        if(list.isEmpty()){
            return "mysql";
        }
        return list.get(0).getSourceName();
    }

    @Override
    public CheckResult<List<com.xayy.mgt.model.vo.TelemetryVo>> getTelemetry(TelemetryVo telemetryVo) {
        // 获取遥测表信息
        CheckResult<String> nodeTelemetryName = systemTelemetryService.getNodeTelemetryName(telemetryVo.getNodeId());
        if (nodeTelemetryName.no())
            return CheckResult.fail(nodeTelemetryName.getCheckMsg());
        String telemetryName = nodeTelemetryName.getData();
        //todo 找卫星下得表
        StringBuilder sql = new StringBuilder();
        sql.append("`");
        sql.append(telemetryVo.getParamCode());
        sql.append("`");

        Date startTime = telemetryVo.getEvaluationTime();
        Integer duration = telemetryVo.getDuration();
        Calendar calendar = CalendarUtil.calendar(startTime);
        calendar.add(Calendar.SECOND, duration * 60);
        Date endTime = calendar.getTime();

        TelemetryDto telemetryDto = new TelemetryDto();
        telemetryDto.setTableName("health_xw."+telemetryName);
        telemetryDto.setSatelliteCode(bayesArgs.getNodeCode());
        telemetryDto.setSatelliteId(telemetryVo.getSatelliteId());
        telemetryDto.setNodeId(telemetryVo.getNodeId());
        telemetryDto.setParam(changeSql(sql.toString()));
        telemetryDto.setStartTime(startTime);
        telemetryDto.setEndTime(endTime);
        telemetryDto.setStep(telemetryVo.getStep());
        List<com.xayy.mgt.model.vo.TelemetryVo> maps;
        try {
            telemetryDto.setSourceName(getDataBaseSource());
            maps = bayesMapper.selectTelemetry(telemetryDto);
        } catch (Exception e) {
            log.error(e.getMessage());
            return CheckResult.fail("遥测表中不存在所查参数");
        }
        return CheckResult.success(maps);
    }

    @Override
    public List<List<String>> getNodeCodeArray(String nodeId) {
        /*查询节点下面的所有卫星编码*/
        List<Map<String,Object>> mapperList = nodeInfoMapper.getNodeCodeArray(nodeId);
        Map<String,List<String>> nodeMap= new LinkedHashMap<>(16);
        /*根据PID分组*/
        mapperList.forEach(item ->{
            String key = item.get("PID").toString();
            String value = "'"+ item.get("NODECODE").toString()+"'";
            if(nodeMap.containsKey(key)){
                nodeMap.get(key).add(value);
            }else{
                List<String> valueList = new ArrayList<>();
                valueList.add(value);
                nodeMap.put(key,valueList);
            }
        });
        /*处理为二维数组*/
        List<List<String>> returnList = new ArrayList<>();
        nodeMap.forEach((k,v) -> returnList.add(v));
        return returnList;
    }


    /**
     * 获取在开始时间和结束时间内的日期时间段集合
     *
     * @param start 开始时间
     * @param end   结束时间
     * @return 时间天数集合
     */
    public static List<Date> dateZones(LocalDateTime start, LocalDateTime end) {
        return Stream.iterate(start.toLocalDate(), x -> x.plusDays(1)).limit(ChronoUnit.DAYS.between(start, end) + 1)
                .map(e -> Date.from(e.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()))
                .collect(Collectors.toList());
    }

    @Override
    public CheckResult<Object> deleteNodeInfo(Long id) {
        nodeInfoMapper.deleteNodeInfo(id);
        return CheckResult.success("删除成功");
    }
}
